package edu.bit.water.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.Pattern.Flag;

import edu.bit.water.dao.MetaSensorDao;
import edu.bit.water.entity.MetaSensor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import edu.bit.water.dao.ChartDao;
import edu.bit.water.dao.EntitySensorDao;
import edu.bit.water.entity.Chart;

@Service
public class EntitySensorService {

	@Autowired
	private EntitySensorDao entitySensorDao;
	@Autowired
	ChartDao chartDao;
	@Autowired
	private MetaSensorDao metaSensorDao;


	/**
	 * 实体设备表插入数据
	 *
	 * @param list Values值
	 * @return 成功返回1，失败返回0
	 */
	public Map<String, String> insertEntitySensor(List<Object> list) {
		Map<String, String> modelMap = new HashMap<>();
		Map<String, Object> insertMap = new HashMap<>();
		//String stringSum = "id,name,sort,workshop,object_name,unit,operator,";
		String stringSum = "id";
		List<String> listColunm = new ArrayList<>();
		for(int i = 0; i < list.size(); i = i + 2) {
			listColunm.add(list.get(i).toString());
		}
		for (String string : listColunm) {
			stringSum = stringSum + " ," + string;
		}
		List<String> valueList = new ArrayList<>();
		Integer id = entitySensorDao.getMaxId();
		if (id != null) {
			valueList.add("" + (id+1));
		} else{
			valueList.add("" + 0);
		}
		for(int i=1;i<list.size();i = i + 2){
			valueList.add("" + list.get(i).toString());
		}

		insertMap.put("lineList", valueList);
		insertMap.put("lineColumn", stringSum);
		//System.out.println(insertMap);


		try {
			int n = entitySensorDao.insertEntitySensor(insertMap);
			if (n == 1) {
				modelMap.put("status", "success");
				return modelMap;
			}
			else {
				modelMap.put("status", "failed");
				return modelMap;
			}
		} catch (DuplicateKeyException e) {
			// TODO: handle exception
			modelMap.put("status", "failed");
			modelMap.put("msg", "设备编号已存在，请重新输入");
			return modelMap;
		}
	}

	/**
	 * 实体设备表查询设备是否已删除
	 *
	 * @param id 数据行的id
	 * @return 成功返回1，失败返回0
	 */
	public int queryEntityStatus(int id){
		return 1;
	}

	/**
	 * 实体设备表删除数据
	 *
	 * @param listId 删除数据行的id
	 * @return 成功返回1，失败返回0
	 */
	public int deleteEntitySensor(List<Integer> listId) {
		// 使用增强for循环进行删除
		try {
			for (int id : listId) {
//				String name = entitySensorDao.selectNameById(id);
				String name = "搞不懂";
				entitySensorDao.deleteEntitySensor(id);
				List<Chart> charts = chartDao.selectChart();
				for(Chart chart:charts) {
					boolean flag = false;
					JSONObject jsonObject = JSONObject.parseObject(chart.getData());
					JSONArray jsonArray = (JSONArray) jsonObject.get("nodeDataArray");
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject jsonObjectTemp = jsonArray.getJSONObject(i);
						String dataName = jsonObjectTemp.getString("name");
						if (name.equals(dataName)) {
							jsonArray.remove(i);
							flag = true;
						}
					}
					if (flag) {
						chart.setData(jsonObject.toString());
						chartDao.updateChart(chart);
					}
				}
			}
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 实体设备表查询数据
	 *
	 * @return 成功返回1，失败返回0
	 */
	public List<Map<String, Object>> selectEntitySensor(String techProcessId) {
		return entitySensorDao.selectEntitySensor(techProcessId);
	}

	/**
	 * 实体设备表更新数据
	 *
	 * @return 成功返回1，失败返回0
	 */
	public Map<String, String> updateEntitySensor(List<Object> list) {

		boolean flag = true;
		Map<String, String> modelMap = new HashMap<>();
		String sql = "";
		for (int i = 2; i < list.size(); i = i + 2) {
			String elemType = entitySensorDao.queryElemType(list.get(i).toString());//查询列的数据类型
			if(elemType.equals("字符型")) {
				if (i == 2) {
					sql = sql + list.get(i).toString() + "=" + "\'" + list.get(i + 1) + "\'";
				} else {
					sql = sql + ", " + list.get(i).toString() + "=" + "\'" + list.get(i + 1) + "\'";
				}
			}
			else {
				if (i == 2) {
					sql = sql + list.get(i).toString() + "=" + list.get(i + 1);
				} else {
					sql = sql + ", " + list.get(i).toString() + "=" + list.get(i + 1);
				}
			}
		}
		Map<String, Object> map = new HashMap<>();
		map.put("id", list.get(1));
		map.put("sql", sql);
		try {
			int n = entitySensorDao.updateEntitySensor(map);
			if (n == 1) {
				if (flag) {
					List<Chart> charts = chartDao.selectChart();
					for(Chart chart:charts) {
						boolean flag1 = false;
						JSONObject jsonObject = JSONObject.parseObject(chart.getData());
						JSONArray jsonArray = (JSONArray) jsonObject.get("nodeDataArray");
						for (int i = 0; i < jsonArray.size(); i++) {
							JSONObject jsonObjectTemp = jsonArray.getJSONObject(i);
							String dataName = jsonObjectTemp.getString("name");
//							if (tempName.equals(dataName)) {
//								jsonObjectTemp.replace("name", changedName);
//								flag1 = true;
//							}
						}
						if (flag1) {
							chart.setData(jsonObject.toString());
							chartDao.updateChart(chart);
						}
					}
				}
				modelMap.put("status", "success");
				return modelMap;
			}
			else {
				modelMap.put("status", "failed");
				return modelMap;
			}
		} catch (DuplicateKeyException e) {
			modelMap.put("status", "failed");
			modelMap.put("msg", "设备编号已存在，请重新输入");
			return modelMap;
		}
	}

	public List<String> selectEntitySensorName() {
		return entitySensorDao.selectEntitySensorName();
	}

	public String querySensorName(String businessId, String sensorRowId){
		return entitySensorDao.queryNameBySensorRowId(businessId,sensorRowId);
	}
}
